package hk.ust.comp3111.ustnutrition;

import hk.ust.comp3111.ustnutrition.data.ApiHandler;
import hk.ust.comp3111.ustnutrition.data.DataAccessor;
import hk.ust.comp3111.ustnutrition.data.json.ApiResponseRank;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class UserRankActivity extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_rank);
		
		setTitle("TOP 10 Ranking");
		
		rank = (TextView)this.findViewById(R.id.rank);

		top10 = (ListView)this.findViewById(R.id.top10);
		top10.setBackgroundColor(getResources().getColor(R.color.background));

		rank.setVisibility(View.GONE);
		DataAccessor.Instance.rank(new ApiHandler<ApiResponseRank>()
				{
					@Override
					public void onSuccess(ApiResponseRank response)
					{
						loadData(response);
					}

					@Override
					public void onFailure(String message)
					{
					}
				});
	}
	
	ListView top10;
	TextView rank;

	private void loadData(ApiResponseRank data)
	{
		MyAdapter adapter = new MyAdapter();
		for (int i = 0; i < data.getLength(); ++i)
		{
			Datum d = new Datum();
			d.name = data.getName(i);
			d.score = data.getScore(i);
			adapter.add(d);
		}
		top10.setAdapter(adapter);
		if(data.getRank() != null)
		{
			rank.setText("My Rank is " + data.getRank());
			rank.setVisibility(View.VISIBLE);
		}
	}

	private static class Datum
	{
		public String name;
		public double score;
	}

	private class MyAdapter extends ArrayAdapter<Datum>
	{
		public MyAdapter()
		{
			super(UserRankActivity.this, android.R.layout.simple_list_item_1);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			LinearLayout v = (LinearLayout)convertView;
			if (v == null)
			{
				v = (LinearLayout)LayoutInflater.from(UserRankActivity.this)
						.inflate(R.layout.rank_card, parent, false);
			}

			Datum d = getItem(position);
			((TextView)v.findViewById(R.id.name)).setText(d.name);
			((TextView)v.findViewById(R.id.score)).setText(String.format("%.2f",
					d.score));
			return v;
		}
	}
}
